#include "xmlparser.h"

XmlParser::XmlParser(QObject *parent) :
    QObject(parent)
{
}


void XmlParser::setParsetFile(const QString& xmlProPath)
{
    QFile file(xmlProPath);
    if (file.exists())
    {
        this->parser(xmlProPath);
    } else {
        emit parserFinish(-1);
    }
}


void XmlParser::parser(const QString& xmlProPath)
{
    QFile file(xmlProPath);
    QFileInfo info(xmlProPath);

    QString rootName = "gl_" + info.baseName();
//    qDebug() << "fileName=====>" << rootName << xmlProPath << info.absolutePath() << info.absoluteFilePath();

    QString errMsg;
    int errLine;
    int errColumn;
    QDomDocument doc;

    if (!doc.setContent(&file, true, &errMsg, &errLine, &errColumn))
    {
        logger()->warn(tr("parser update xml err, errLine:%1, errColum:%2,"
                       "errMsg:%3\n").arg(errLine).arg(errColumn).arg(errMsg));
//        qDebug() << "doc setContent err==>" << "errline:" << errLine <<
//                    "errColum:" << errColumn << "err:" << errMsg;
        emit parserFinish(-2);

    }
    QDomElement root = doc.documentElement();
    if (root.tagName() != rootName)
    {
        logger()->warn(tr("parser update xml err, root tagName err, err root tagName:%1, right root tagName:%2\n")
                       .arg(root.tagName()).arg(rootName));
        emit parserFinish(-3);
        return;
    }

    QString project = root.attribute("Project");
    QString publishTime = root.attribute("PublishTime");
    QString dbPath = root.attribute("DatabasePath");
    QString resourcePath = root.attribute("ResourceDir");


//    qDebug() << "proValue====>" << project << publishTime << dbPath;

    if (project == "SLCD")
    {
//        qDebug() << "emit success";
        emit parserFinish(0, info.absoluteFilePath(), publishTime, dbPath, resourcePath);
        return;
    } else {
        emit parserFinish(-4);
        return;
    }
}

int  XmlParser::parserFile(const QString& xmlProPath, QString& publishTime, QString& dbPath, QString& resourcePath)
{
    QFile file1(xmlProPath);
    if (!file1.exists())
    {
        return -1;
    }


    QFile file(xmlProPath);
    QFileInfo info(xmlProPath);

    QString rootName = "gl_" + info.baseName();
//    qDebug() << "fileName=====>" << rootName << xmlProPath << info.absolutePath() << info.absoluteFilePath();

    QString errMsg;
    int errLine;
    int errColumn;
    QDomDocument doc;

    if (!doc.setContent(&file, true, &errMsg, &errLine, &errColumn))
    {
//        qDebug() << "doc setContent err==>" << "errline:" << errLine << "errColum:" << errColumn << "err:" << errMsg;
//        emit parserFinish(-2);
        return -2;

    }
    QDomElement root = doc.documentElement();
    if (root.tagName() != rootName)
    {
//        emit parserFinish(-3);
//        return;
        return -3;
    }

    QString project = root.attribute("Project");
    QString publish = root.attribute("PublishTime");
    QString db = root.attribute("DatabasePath");
    QString resource = root.attribute("ResourceDir");


//    qDebug() << "proValue====>" << project << publish << db;

    if (project == "SLCD")
    {
//        qDebug() << "emit success";
        publishTime = publish;
        dbPath = db;
        resourcePath = resource;
//        emit parserFinish(0, info.absolutePath(), publishTime, dbPath, resourcePath);
        return 0;
    } else {
//        emit parserFinish(-4);
        return -4;
    }
}

ProjectStruct XmlParser::parsetProFile(const QString& xmlProPath)
{
    ProjectStruct proStruct;

    QFile file1(xmlProPath);
    if (!file1.exists())
    {
        return proStruct;
    }


    QFile file(xmlProPath);
    QFileInfo info(xmlProPath);

    QString rootName = "gl_" + info.baseName();
//    qDebug() << "fileName=====>" << rootName << xmlProPath << info.absolutePath() << info.absoluteFilePath();

    QString errMsg;
    int errLine;
    int errColumn;
    QDomDocument doc;

    if (!doc.setContent(&file, true, &errMsg, &errLine, &errColumn))
    {
//        qDebug() << "doc setContent err==>" << "errline:" << errLine << "errColum:" << errColumn << "err:" << errMsg;
//        emit parserFinish(-2);
        return proStruct;

    }

    QDomElement root = doc.documentElement();
    if (root.tagName() != rootName)
    {
//        emit parserFinish(-3);
//        return;
        return proStruct;
    }

    QString project = root.attribute("Project");
    QString publish = root.attribute("PublishTime");
    QString db = root.attribute("DatabasePath");
    QString resource = root.attribute("ResourceDir");

    proStruct.proPath = xmlProPath;
    proStruct.publishTime = publish;
    proStruct.dbPath = g_installPath + "/" + db;
    proStruct.resoucePath = resource + "/";

    QString path = tr("%1/%2").arg(g_installPath).arg(proStruct.resoucePath);
    path.replace("\\", "/");

    proStruct.resourceSize = this->countDirSize(path);
//    proStruct.resoucePath = resource;

    return proStruct;
}


//计算文件夹的大小
qint64 XmlParser::countDirSize(const QString& dirPath)
{
#ifdef _TTY_POSIX_

    struct stat     stat;
    struct dirent   *dirp;
    DIR             *dp;
    char            *ptr;


    ptr = (char *)malloc(sizeof(char) * 1024);

    int fileSize = 0;

    dp = opendir(dirPath.toLatin1().data());
    if (dp == NULL)
    {
        qDebug() << "open dp err==>" << dirPath.toLatin1().data();
        return fileSize;
    }

    while((dirp = readdir(dp)) != NULL)
    {
        if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
        {
            continue;
        }

        memset(ptr, 0, 1024);
        strcpy(ptr, dirPath.toLatin1().data());
        strcat(ptr, "/");
        strcat(ptr, dirp->d_name);
        if (lstat(ptr, &stat) < 0)
        {
//            qDebug() << "err fileName==>" << ptr;
            continue;
        }

        if (!S_ISDIR(stat.st_mode))
        {
            fileSize += stat.st_size;
        } else {
            QString dirPath = QString::fromLocal8Bit(ptr);
            fileSize += this->countDirSize(dirPath);
        }
    }

    //linux中每个文件夹也占4096个字节，右键属性中的大小已经包含这个大小,所以要算占用空间的大小
    //这个是要加进去，不过在WIN下只计算纯粹大小，所以此处不加进去
    //fileSize += 4096;

//    qDebug() << fileSize << "ptr===>" << dirPath;

    free(ptr);
    closedir(dp);
    return fileSize;
#else

    //linux下用此算法基本正确，但如果有涉及到中文名字，那么中文名将不能识别，
    //从而导致大小计算出错
    QDir dir(dirPath);
    QFileInfoList infoList = dir.entryInfoList();

    qint64 fileSize = 0;

    for(int i = 0; i < infoList.count(); i++)
    {
        QFileInfo info = infoList.at(i);

        if(info.fileName() == "." || info.fileName() == "..")
            continue;

        if (dirPath.contains("PISPlayer-build-desktop/Resource/AD"))
            qDebug() << infoList.count() << i << "infoFileName===>:" << info.fileName();

        if (info.isDir())
        {
            fileSize += this->countDirSize(info.absoluteFilePath());
        } else {
            fileSize += info.size();
        }
    }
    fileSize += 4096;

    return fileSize;
#endif
}

